<?php
/**
 * This is the template for generating a controller class file for CRUD feature.
 * The following variables are available in this template:
 * - $this: the BootCrudCode object
 */
?>
<?php echo "<?php\n"; ?>

class <?php echo $this->controllerClass; ?> extends <?php echo $this->baseControllerClass . "\n"; ?>
{
	public $menuRoute = '/<?php echo $this->controllerId ?>/index';

	/**
	* 首页
	*/
	public function actionIndex()
	{
		$model=new <?php echo $this->modelClass; ?>('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['<?php echo $this->modelClass; ?>'])) {
			$model->attributes=$_GET['<?php echo $this->modelClass; ?>'];
		}
		$this->render('index',array('model'=>$model));
	}

	/**
	* 查看
	* @param integer $id
	*/
	public function actionView($id)
	{
		$this->render('view', array('model'=>$this->loadModel($id)));
	}

	/**
	* 创建
	*/
	public function actionCreate()
	{
		$model=new <?php echo $this->modelClass; ?>;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['<?php echo $this->modelClass; ?>']))
		{
			$model->attributes=$_POST['<?php echo $this->modelClass; ?>'];
			if($model->save()) {
				$this->redirect(array('view', 'id'=>$model-><?php echo $this->tableSchema->primaryKey; ?>));
			}
		}

		$this->render('create', array(
			'model'=>$model,
		));
	}

	/**
	* 更新
	*
	* @param integer $id
	*/
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['<?php echo $this->modelClass; ?>']))
		{
			$model->attributes=$_POST['<?php echo $this->modelClass; ?>'];
			if($model->save()) {
				$this->redirect(array('view','id'=>$model-><?php echo $this->tableSchema->primaryKey; ?>));
			}
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	* 删除
	*
	* @param integer $id the ID of the model to be deleted
	* @throws CHttpException
	*/
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			if(!isset($_GET['ajax'])) {
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index'));
			}
		} else {
			throw new CHttpException(405,'无效的请求，请重试');
		}
	}

	/**
	* @param integer $id
	* @return <?php echo $this->modelClass; echo "\n" ?>
	* @throws CHttpException
	*/
	public function loadModel($id)
	{
		$model=<?php echo $this->modelClass; ?>::model()->findByPk($id);
		if($model===null) {
			throw new CHttpException(404,'页面没有找到');
		}
		return $model;
	}

	/**
	* ajax 验证
	*
	* @param CModel
	*/
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='<?php echo $this->class2id($this->modelClass); ?>-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
